package org.cypress.rtpack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cypress.rtpack.common.core.Result;
import org.cypress.rtpack.common.exception.BizException;
import org.cypress.rtpack.common.exception.ExceptionCode;
import org.cypress.rtpack.entity.RtpackHostname;
import org.cypress.rtpack.entity.RtpackMoniip;
import org.cypress.rtpack.entity.SoeSysname;
import org.cypress.rtpack.mapper.SoeSysnameMapper;
import org.cypress.rtpack.service.ISoeSysnameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author getty
 */
@Service
public class SoeSysnameServiceImpl extends ServiceImpl<SoeSysnameMapper, SoeSysname> implements ISoeSysnameService {
    @Autowired
    SoeSysnameMapper soeSysnameMapper;

    @Override
    public SoeSysname getById(Integer id) {
        LambdaQueryWrapper<SoeSysname> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SoeSysname::getId, id);
        SoeSysname soeSysname = this.getBaseMapper().selectOne(queryWrapper);
        return soeSysname;
    }

    @Override
    public List<SoeSysname> getAll() {
        LambdaQueryWrapper<SoeSysname> queryWrapper = new LambdaQueryWrapper<>();
        List<SoeSysname> getList = this.getBaseMapper().selectList(queryWrapper);
        return getList;
    }

    @Override
    public Result<SoeSysname> insertWithCheck(SoeSysname entity) {
        // 检查sysname是否已存在
        QueryWrapper<SoeSysname> wrapper = new QueryWrapper<>();
        wrapper.eq("sysname", entity.getSysname());
        long count = this.count(wrapper);

        if (count > 0) {
            throw new BizException(ExceptionCode.duplicatedError,"系统名称已存在"); // 自定义业务异常
        }

        // 不存在则插入
        this.save(entity);
        return Result.dataOf(entity);
    }

    @Override
    public Result<SoeSysname> gettyUpdateById(SoeSysname inst) {
        // 1. 参数校验
        if (inst == null || inst.getId() == null) {
            throw new IllegalArgumentException("Config or key cannot be null");
        }

        // 2. 检查配置项是否存在
        LambdaQueryWrapper<SoeSysname> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SoeSysname::getId, inst.getId());
        SoeSysname existing = getOne(queryWrapper);

        if (existing == null) {
            throw new RuntimeException("Config with key [" + inst.getId() + "] not found");
        }

        // 3. 检查 sysname 是否与其他记录重复（排除当前 ID）
        if (isSysnameDuplicate(inst.getSysname(), inst.getId())) {
            throw new BizException(ExceptionCode.duplicatedError,"系统名称已存在"); // 自定义业务异常
        }

        // 3. 保留原始ID（防止前端误传ID导致更新错误记录）
        inst.setId(existing.getId());

        // 4. 执行更新（MyBatis-Plus的updateById是原子操作）
        boolean success = updateById(inst);

        if (!success) {
            throw new RuntimeException("Update sysname failed");
        }

        // 5. 返回更新后的完整数据（避免返回前端可能修改过的对象）
        return Result.dataOf(getById(inst.getId()));
    }

    /**
     * 检查 sysname 是否与其他记录重复（排除指定 ID）
     */
    private boolean isSysnameDuplicate(String sysname, int excludeId) {
        LambdaQueryWrapper<SoeSysname> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SoeSysname::getSysname, sysname)
                .ne(SoeSysname::getId, excludeId); // 排除当前记录
        return count(wrapper) > 0;
    }

    @Override
    public int gettyDeleteById(int id){
        int delC = soeSysnameMapper.deleteById(id);
        if(delC < 1){
            throw new BizException(ExceptionCode.paramError,String.format("未找到对应id=%d",id));
        }
        return delC;
    }
}
